#include "StdAfx.h"
#include "DApplicationSFML.h"
#include <SFML/Graphics.hpp>
#include "../Game/DGame.h"
#include "../Engine/DRendererSFML.h"
#include "../Engine/DInput.h"
#include "../DGlobals.h"

DApplicationSFML::DApplicationSFML(void)
: DIApplication()
{
}

DApplicationSFML::~DApplicationSFML(void)
{
}

void DApplicationSFML::init()
{
	createAppWindow(sf::VideoMode(DGlobals::instance().screenWidth(),
								  DGlobals::instance().screenHeight()), "Cybermyth", false);
    
    m_device->ShowMouseCursor(false);

	boost::shared_ptr<DIRenderer> renderer = boost::shared_ptr<DIRenderer>(new DRendererSFML(m_device));

	boost::shared_ptr<DInput> input = boost::shared_ptr<DInputSFML>(new DInputSFML(m_device->GetInput()));
    m_game = boost::shared_ptr<DGame>(new DGame(renderer, input));

    m_game->init();
}

void DApplicationSFML::run()
{
	// perform event loop
	sf::Clock Clock;

	while (m_device->IsOpened())
    {
        // Process events
        sf::Event Event;
        while (m_device->GetEvent(Event))
        {
			// Close window : exit
            if (Event.Type == sf::Event::Closed)
                m_device->Close();

            // Escape key : exit
            if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
                m_device->Close();
        }

		float ElapsedTime = Clock.GetElapsedTime();
        Clock.Reset();

		update(ElapsedTime);

		m_device->Clear();
		render();
		m_device->Display();
	}
}

void DApplicationSFML::cleanup()
{

}

void DApplicationSFML::update(float dt)
{
    if(m_game)
    {
        m_game->update(dt);
    }
}

void DApplicationSFML::render()
{
	if(m_game)
    {
        m_game->render();
    }
}

void DApplicationSFML::createAppWindow(const sf::VideoMode& videoMode, const std::string& windowTitle, bool bFullScreen)
{
	unsigned int windowStyle = sf::Style::Resize | sf::Style::Close;

	if(bFullScreen)
	{
		windowStyle = sf::Style::Fullscreen;
	}

	m_device = boost::shared_ptr<sf::RenderWindow>(new sf::RenderWindow(videoMode, windowTitle, windowStyle));
	m_device->UseVerticalSync(false);
}